//
//  Listing6.m
//  SchmoozingExamples
//
//  Created by garrison on Fri Apr 20 2001.
//  Copyright (c) 2001 Standard Orbit Software, LLC. All rights reserved.
//
//  Permission is granted to use this code for any purpose, at your own risk.
//  No warranties are expressed or implied.

#import <Foundation/Foundation.h>
#import <OmniNetworking/OmniNetworking.h>

// A Threaded Concurrent TCP Server Using OmniNetworking

#import "Connection.h"

int main( int argc, char** argv ) {
    ONTCPSocket *serverSocket;
    unsigned short serverPort = 1701;
    NSAutoreleasePool *mainPool;
    
    mainPool = [[NSAutoreleasePool alloc] init];
    
    serverSocket = [ONTCPSocket tcpSocket];
    // Master Step 1. Allocate a socket
    
    [serverSocket startListeningOnLocalPort: serverPort];
    // Master Step 2. Establish a listener
    
    
    while (1) {
            NSAutoreleasePool *loopPool = nil;
            Connection *client = nil;
            ONTCPSocket *connectionSocket = nil;
                
            loopPool = [[NSAutoreleasePool alloc] init];
    
            NSLog(@"Main thread listening for next connection");
            connectionSocket = [serverSocket acceptConnectionOnNewSocket];
            // Master Step 3. Accept new connections
    
            client = [[Connection alloc] initWithConnectedSocket:connectionSocket];
            [client autorelease];
            // Slave Step 1. Receive the connectionÕs socket in our connection
            // handling object.
    
            NSLog(@"Detaching thread to handle the connection");
            [NSThread detachNewThreadSelector:@selector(processConnection)
                        toTarget:client withObject:nil];
            // Slave Step 2. Interact with the client, in a separate thread,
            // by way of ConnectionÕs processConnection: method.
            // Slave Step 3. Closing the connection, is handled in the spawned thread.
    
            [loopPool release];
    }
    
    [mainPool release];    
    return(0);
    exit(0);
}